import axios from 'axios'
import {
  Message
} from 'element-ui'
import store from '@/store'
import router from "@/router"
import {
  getTimeStamp
} from './auth'


// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // 基地址
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

// 设置超时时间
const timeout = 3600

service.interceptors.request.use(async config => {
  if (store.getters.token) {
    // 拿到获得Token时的时间戳
    let timeStamp = getTimeStamp()
    // 拿到当前时间
    let current = Date.now()
    // 拿到当前时间-初始时间得到过了多少毫秒，除以1000代表转换成秒
    let time = (current - timeStamp) / 1000

    if (time >= timeout) {
      await store.dispatch('user/logout')
      Message.error('登录状态已过期，请重新登录！')
      router.push('/login')
      return config
    }
    config.headers.Authorization = 'Bearer ' + store.getters.token
  }
  return config;
}, error => {
  return Promise.reject(error)
})

service.interceptors.response.use(response => {
  let res = response.data
  if (res.success) {
    return res
  } else {
    Message.error(res.message)
    return Promise.reject(res.message)
  }
}, error => {
  if (error.response && error.response.data && error.response.data.code === 10002) {
    store.dispatch('user/logout')
    Message.error('登录状态已过期，请重新登录！')
    router.push('/login')
  } else {
    Message.error(error.message)
  }
  return Promise.reject(error)
})



export default service
